const service = require('../service/user.service')
const { PRIVATE_KEY } = require('../app/config')
const jwt = require('jsonwebtoken')
const errorType = require('../constant/errorType')
class UserController {
  async create(ctx, next) {
    // 1. 获取数据
    const user = ctx.request.body
    // 2. 数据库操作 插入数据
    const result = await service.create(user)
    // 3. 返回数据
    ctx.body = {
      status: 200,
      msg: '注册成功~'
    }
  }
  login(ctx, next) {
    // 1. 颁发token
    const { id, user } = ctx.user
    const token = jwt.sign({ id, user }, PRIVATE_KEY, {
      expiresIn: 60 * 60 * 24,
      algorithm: 'RS256'
    });
    // 2. 返回数据
    ctx.status = 200
    ctx.body = {
      id: id,
      user: user,
      status: 200,
      token: token,
      msg: '登录成功~'
    }
    console.log('登录成功');
  }
  async loginMobile(ctx, next) {
    const { user } = ctx.request.body
    const res = await service.getUserByName(user)
    if (res.length === 0) return ctx.app.emit('error', new Error(errorType.USER_NOT_EXISTS), ctx)
    ctx.user = res[0]
    await next()
  }
}
module.exports = new UserController()